package main

import (
	"encoding/json"
	"fmt"
	u "gongxiangke/utils"
	"sync"
	"time"

	"github.com/robfig/cron"

	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

var (
	wg           sync.WaitGroup
	cooker       = ""
	applyTaskUrl = "http://ddd.turenkeji.com/mobile/task/applytask?ww="
	userAgent    = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
)

const (
	loginUrl = "http://ddd.turenkeji.com/mobile/user/login"

	cancelApplyTaskUrl = "http://ddd.turenkeji.com/mobile/task/cancelapply"

	getUserInfoUrl = "http://ddd.turenkeji.com/mobile/user/getuserinfo"
)

func main() {

	wg.Add(1)
	// 主要任务
	c := cron.New()
	//间隔一定时间分钟 申请一次任务
	c.AddFunc(u.Con.CronStr, func() {
		u.Lg.Info("============start===================")
		//登陆
		login()
		// 关闭任务
		cancelTask()
		// 申请任务
		apllyTask()

		EveryGetUser()
		u.Lg.Info("============end===================")
	})
	c.Start()

	wg.Wait()
}

// 实现共享客的登陆
func login() {

	data := make(url.Values)
	data["ww"] = []string{u.Con.Username}
	data["pwd"] = []string{u.Con.Password}
	resp, err := http.PostForm(loginUrl, data)
	//client := &http.Client{}
	//request, err := http.NewRequest("post", loginUrl, nil)
	//request.Header.Add("User-Agent", userAgent)
	//request.Header.Add("Cookie", "PHPSESSID=cjmtjm048gq2odqukgg21pphtd")
	//request.Header.Add("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundaryR0LDnw4o9ldytzrQ")
	//request.Form = data
	//resp, err := client.Do(request)

	if err != nil {
		panic(err)
	}
	loginRespData := make([]byte, 1<<10)

	cookieStr := resp.Header.Get("Set-Cookie")
	split := strings.Split(cookieStr, ";")
	cooker = split[0]
	u.Lg.Info(" login success,cooker =%v", cooker)
	readInt, _ := resp.Body.Read(loginRespData)
	loginRespStr := string(loginRespData[:readInt])
	var loginRespDTO RespDTO
	json.Unmarshal([]byte(loginRespStr), &loginRespDTO)
	u.Lg.Info("登陆成功相应的数据=%s", loginRespDTO)

}

//接口响应数据
type RespDTO struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

//任务申请的，接口调用
func apllyTask() {

	client := &http.Client{}
	//打印本次请求的 cooker
	u.Lg.Info("cooker applyTask = %s", cooker)
	//将任务申请链接和用户名称拼接在一起
	applyTaskUrl = fmt.Sprintf("%s%s", applyTaskUrl, u.Con.Username)
	// 使用get 请求
	req, _ := http.NewRequest("GET", applyTaskUrl, nil)
	splitStr := strings.Split(cooker, "=")

	u.Lg.Info("%v", splitStr)
	//可以添加多个cookie
	cookie := &http.Cookie{Name: splitStr[0], Value: splitStr[1], HttpOnly: true}
	req.AddCookie(cookie)

	resp, _ := client.Do(req)

	defer func() {
		_ = resp.Body.Close()
	}()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		u.Lg.Info("%s", err)
	}
	applyRespStr := string(body)
	var applyRespDTO RespDTO
	json.Unmarshal([]byte(applyRespStr), &applyRespDTO)
	u.Lg.Info("任务申请成功相应的数据=%s", applyRespDTO)
}

// 任务取消
func cancelTask() {

	client := &http.Client{}
	u.Lg.Info("cooker cancelTask =%s", cooker)
	req, _ := http.NewRequest("POST", cancelApplyTaskUrl, nil)
	splitStr := strings.Split(cooker, "=")

	//可以添加多个cookie
	cookie := &http.Cookie{Name: splitStr[0], Value: splitStr[1], HttpOnly: true}
	req.AddCookie(cookie)

	//添加参数
	reqParam := make(url.Values)
	reqParam.Set("ww", u.Con.Username)
	resp, _ := client.Do(req)

	defer func() {
		_ = resp.Body.Close()

	}()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		u.Lg.Info("%s", err)
	}
	concalApplyRespStr := string(body)
	var concalApplyRespDTO RespDTO
	json.Unmarshal([]byte(concalApplyRespStr), &concalApplyRespDTO)
	u.Lg.Info("任务取消成功=%s", concalApplyRespDTO)
}
func EveryGetUser() {
	for {
		getUserInfo()
		time.Sleep(time.Second * 10)
	}

}
func getUserInfo() {
	client := &http.Client{}
	//打印本次请求的 cooker
	u.Lg.Info("cooker getUserInfo = %s", cooker)

	// 使用get 请求
	req, _ := http.NewRequest("GET", getUserInfoUrl, nil)
	splitStr := strings.Split(cooker, "=")

	u.Lg.Info("%v", splitStr)
	//可以添加多个cookie
	cookie := &http.Cookie{Name: splitStr[0], Value: splitStr[1], HttpOnly: true}
	req.AddCookie(cookie)
	resp, _ := client.Do(req)
	defer func() {
		_ = resp.Body.Close()
	}()
	all, _ := ioutil.ReadAll(resp.Body)
	var respD RespDTO
	json.Unmarshal(all, &respD)
	u.Lg.Info("用户返回=%v", respD)

}
